
#include <stdint.h>
#include <string.h>
//PICC
#include "CardPort.h"
#include "CardPrivate.h"
#include "ISO14443p3a.h"
//ICC

#include "Slot.h"

#include "CardCommandDefine.h"

#include "Debug.h"

#define DAPDU	0

extern slot_t Slot[];

/*

*/
int Card_ExchangeApdu(uint8_t card, uint8_t capdu[], uint16_t clen, uint8_t* rapdu, uint16_t* rlen){
	static uint8_t apdu_buf[270];
	uint16_t txlen;
	unsigned int rxlen = 0;
	int ret = -1;

	MDBG_PRINT(DAPDU, "card: %u\r\n", card);
	MDBG_WRITE(DAPDU, "capdu:");MDBG_PRINT_BUF(DAPDU, capdu, clen); MDBG_WRITE(DAPDU, "\r\n");
	if(card == Card_PICC){
		ret = Port_Picc_Exchange(capdu, clen, apdu_buf, &rxlen);
	}
#if 0
	else
	if(card == Card_SAM){
		uint32_t r_len;
		ret = Slot_ExchangAPDU(Slot, capdu, clen, apdu_buf, &r_len);
		if(ret == 0){
			rxlen = r_len;
		}
	}
#endif 
	
	if(ret){
		return ret;
	}
	
	if(rxlen < 2){
		return -2;
	}

	MDBG_WRITE(DAPDU, "rapdu:");MDBG_PRINT_BUF(DAPDU, apdu_buf, rxlen); MDBG_WRITE(DAPDU, "\r\n");
	if(memcmp((uint8_t []){0x90, 0x00}, &apdu_buf[rxlen - 2], 2)){
		return 1;
	}
	if(rlen){
		*rlen = rxlen - 2;
	}
	if(rapdu){
		memcpy(rapdu, apdu_buf, rxlen - 2);
	}
	return ret;
}





